<style>
    .warning-msg { }
    .warning-msg-content { background-color: #FFFFCC; border: 1px solid #FFFF33; padding: 10px; margin-bottom: 15px; color: #666; }
        .warning-msg-content i { display: inline-block; font-size: 16px; margin-right: 5px; color: red; }
        .warning-msg-content p { display: inline-block; }
        .warning-msg-content a { color: #20a53a; }
            .warning-msg-content a:hover { color: #23527c; }
    #container { width: 100%; height: 450px; }
    #suggestionList { position: absolute; z-index: 999999; background: #fff; padding: 10px; }
</style>
<body>
    <script type="text/html" template lay-done="layui.data.done(d);">
        <div class="layui-form coreshop-form layui-form-pane" lay-filter="LAY-app-CoreCmsEnterprise-MapForm" id="LAY-app-CoreCmsEnterprise-MapForm">
            <input type="hidden" name="coordinate" value="{{d.params.data.oldData}}">

            <div class="layui-form-item">
                <label for="tags" class="layui-form-label">区域</label>
                <div class="layui-input-inline layui-inline-2">
                    <input id="areaName" name="areaName" value="怀化" class="layui-input" lay-reqText="请输入标签" placeholder="请输入标签" />
                </div>
                <label for="tags" class="layui-form-label">详细地址</label>
                <div class="layui-input-inline layui-inline-6">
                    <input id="keyword" name="keyword" oninput="getSuggestions()" class="layui-input" lay-reqText="请输入标签" placeholder="请输入标签" id="place" style="z-index: 99999999" />
                    <ul id="suggestionList">
                    </ul>
                </div>
                <div class="layui-form-mid layui-text-em">先输入区域，再输入模糊地址</div>

                <div class="layui-form-mid" style="padding: 0 !important;float: right">
                    <button type="button" id="save-map" class="layui-btn" lay-submit lay-filter="formDemo">保存当前位置</button>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <div class="layui-input-inline layui-inline-10" id="container" style="min-width: 100%; min-height: 450px;">
                </div>
            </div>
        </div>
    </script>
</body>
<script>
    var $;
    var debug = layui.setter.debug;
    var coordinateBoxIdName;
    var addressBoxIdName;
    var suggest;
    var map;
    var markerLayer;
    var infoWindowList = Array(10);

    layui.data.done = function (d) {
        //开启调试情况下获取接口赋值数据
        if (debug) { console.log(d.params.data); }

        coordinateBoxIdName = d.params.data.coordinateBoxIdName;
        addressBoxIdName = d.params.data.addressBoxIdName;

        console.log(addressBoxIdName);

        layui.use(['admin', 'form', 'coreHelper'], function () {
            $ = layui.$;
            var setter = layui.setter, admin = layui.admin, coreHelper = layui.coreHelper, form = layui.form;
            var layer = layui.layer;

            var center = null;
            var preLocationCenter = $("input[name=coordinate]").val();
            if (preLocationCenter == '') {
                //定义地图中心点坐标
                center = new TMap.LatLng(27.551849, 109.983969)
            } else {
                var arr = preLocationCenter.split(',');
                if (arr.length < 2) {
                    parent.layer.msg("坐标位置错误");
                    return false;
                }
                center = new TMap.LatLng(arr[0], arr[1])
            }

            //定义map变量，调用 TMap.Map() 构造函数创建地图
            map = new TMap.Map(document.getElementById('container'), {
                center: center,//设置地图中心点坐标
                zoom: 17.2,   //设置地图缩放级别
                pitch: 43.5,  //设置俯仰角
                rotation: 0    //设置地图旋转角度
            });
            var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类

            //创建并初始化MultiMarker
            markerLayer = new TMap.MultiMarker({
                map: map,  //指定地图容器
                //样式定义
                styles: {
                    marker: new TMap.MarkerStyle({
                        width: 20, // 样式宽
                        height: 30, // 样式高
                        anchor: { x: 10, y: 30 }, // 描点位置
                    }),
                },
                geometries: [
                    {
                        // 标记位置(纬度，经度，高度)
                        position: center,
                        id: 'marker',
                    },
                ],
            });

            //移除marker事件
            function removeMarker() {
                markerLayer.setGeometries([])
            }

            //监听点击事件添加marker
            map.on("click", (evt) => {
                removeMarker();
                markerLayer.add({
                    position: evt.latLng
                });
            });

            //定义事件处理方法
            var clickHandler = function (evt) {
                var lat = evt.latLng.getLat().toFixed(6);
                var lng = evt.latLng.getLng().toFixed(6);
                console.log("您点击的的坐标是：" + lat + "," + lng);

            }
            //Map实例创建后，通过on方法绑定点击事件
            map.on("click", clickHandler)

            $("#save-map").on('click', function () {

                console.log(markerLayer.geometries);

                parent.$("#" + coordinateBoxIdName).val(markerLayer.geometries[0].position.lat + ',' + markerLayer.geometries[0].position.lng);
                if (addressBoxIdName) {

                    var location = new TMap.LatLng(Number(markerLayer.geometries[0].position.lat), Number(markerLayer.geometries[0].position.lng));
                    geocoder.getAddress({ location: location }) // 将给定的坐标位置转换为地址
                        .then((result) => {
                            console.log(result.result.address);
                            parent.$("#" + addressBoxIdName).val(result.result.address);
                            // 显示搜索到的地址
                        });
                }
                //parent.layer.closeAll();
                parent.layer.close(layer.index);
            });


            form.render(null, 'LAY-app-CoreCmsEnterprise-MapForm');
        });

        // 新建一个地点搜索类
        //suggest = new TMap.service.Suggestion({
        //    // 新建一个关键字输入提示类
        //    pageSize: 10, // 返回结果每页条目数
        //    region: '北京', // 限制城市范围
        //    regionFix: true, // 搜索无结果时是否固定在当前城市
        //});



    };
    function setSuggestion(index) {
        // 点击输入提示后，于地图中用点标记绘制该地点，并显示信息窗体，包含其名称、地址等信息
        infoWindowList.forEach((infoWindow) => {
            infoWindow.close();
        });
        infoWindowList.length = 0;
        document.getElementById('keyword').value = suggestionList[index].title;
        document.getElementById('suggestionList').innerHTML = '';
        markerLayer.setGeometries([]);
        markerLayer.updateGeometries([
            {
                id: '0', // 点标注数据数组
                position: suggestionList[index].location,
            },
        ]);
        var infoWindow = new TMap.InfoWindow({
            map: map,
            position: suggestionList[index].location,
            content: `<h3>${suggestionList[index].title}</h3><p>地址：${suggestionList[index].address}</p>`,
            offset: { x: 0, y: -50 },
        });
        infoWindowList.push(infoWindow);
        map.setCenter(suggestionList[index].location);
        markerLayer.on('click', (e) => {
            infoWindowList[Number(e.geometry.id)].open();
        });
    }


    function getSuggestions() {
        var areaName = document.getElementById('areaName').value;
        if (!areaName) {
            areaName = "怀化";
        }
        suggest = new TMap.service.Suggestion({
            // 新建一个关键字输入提示类
            pageSize: 30, // 返回结果每页条目数
            region: areaName, // 限制城市范围
            regionFix: true, // 搜索无结果时是否固定在当前城市
        });
        // 使用者在搜索框中输入文字时触发
        var suggestionListContainer = document.getElementById('suggestionList');
        suggestionListContainer.innerHTML = '';
        var keyword = document.getElementById('keyword').value;
        if (keyword) {
            suggest
                .getSuggestions({ keyword: keyword, location: map.getCenter() })
                .then((result) => {
                    // 以当前所输入关键字获取输入提示
                    suggestionListContainer.innerHTML = '';
                    suggestionList = result.data;
                    suggestionList.forEach((item, index) => {
                        suggestionListContainer.innerHTML += `<li><a onclick="setSuggestion(${index})">${item.title}<span class="item_info">${item.address}</span></a></li>`;
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        }
    }
</script>